"""
Auto push this repo, try many times until success
"""
import os
from rich import print
import time

MSG_OK = '''[green]
######################
#    Push Success    #
######################
'''

MSG_ERR = '''[red]
#####################
#    Push Failed    #
#####################
'''


def now():
    return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())


def info_print(message):
    print(f'\n[bold yellow](INFO) [/]{message}\n')


def success_print(message):
    print(f'\n[bold green](OK) [/]{message}\n')


def error_print(message):
    print(f'\n[bold red](ERR) [/]{message}\n')


def add():
    """
    ask whether to add files, then auto commit.
    """
    os.system('git status')
    print('[bold green]? Add these files? (Y/n): [/]', end='')
    if input() not in {'Y', 'y', ''}:
        return False
    info_print('Adding changes')
    os.system('git add .')

    print('[bold green]? Input commit message (optional): [/]', end='')
    ask = input()
    if not ask:
        ask = f'Auto commit @ {now()}'
        print(f'[yellow]* Use auto message [green]"{ask}"')
    os.system(f'git commit -m "{ask}"')
    return True


def push():
    """
    Push this repo to remote, try many times until success.
    """
    print('\n[bold green]Begin Pushing Files[/]')
    success = False
    # loop push
    for t in range(5):
        info_print(f'Try push {t + 1} times')
        ret = os.system('git push origin master')
        if ret == 0:
            success_print(f'Push success @ {t} times!')
            success = True
            break
        else:
            error_print('Push failed! Retrying...')
    # show push result
    if not success:
        print(MSG_ERR)
    else:
        print(MSG_OK)
    os.system('timeout /t 5')
    return True


def aio_push():
    if add():
        push()


if __name__ == '__main__':
    aio_push()
